#!/usr/bin/env python

#Author :  Krishna Pattabiraman
#File   :  pytrans.py
#Project:  PyTrans
import urllib
import httplib
import re
import sys

def google_translate(from_lang, to_lang, text):
	params = urllib.urlencode({"langpair":"%s|%s" %(from_lang, to_lang), "text":text,"ie":"UTF8", "oe":"UTF8"})
	conn = httplib.HTTPConnection("translate.google.com")
	conn.request("POST", "/translate_t", params)

	resp = conn.getresponse()
	s = resp.read()
	conn.close()

	match = re.compile('<div id=result_box.*?>(.*?)</div>',re.DOTALL).search(s)
	data = match.groups()[0]
	return unicode(data, "utf-8").strip()
	
conv = "en-de"
while 1:
	conv_line = raw_input(conv+">")
	if conv_line == "":
		continue
	if conv_line == "e2g":
		conv = "en-de"
		continue
	if conv_line == "g2e":
		conv = "de-en"
		continue
	if conv == "en-de":
		string = google_translate('en','de',conv_line)
	else:
		string = google_translate('de','en',conv_line)
	
	print string
